﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml.Linq;

namespace LibTracker
{
    class XMLDataSet : IPostDataSet
    {
        public string XMLFile { get; protected set; }

        // ToDo Возможно будет необходимо определить методы get И set 
        public string TrackNumber { get; protected set; }

        public string CountryDestanationID { get; protected set; }

        public XMLDataSet(string aTrackNumber, string aCountryDestanationID, string PathXml)
        {
            TrackNumber = aTrackNumber;
            CountryDestanationID = aCountryDestanationID;
            XMLFile = LibTracker.Properties.Resources.services;//PathXml;
        }

        public IEnumerable<PostServiceInfo> GetPostServices()
        {
            XDocument xDoc = XDocument.Parse(XMLFile);

            IEnumerable<XElement> services = xDoc.Element("trackchecker.services").Element("servlst").Elements();

            // сделать запрос на осноывнии track number

            var activeServices = services
                .Where(e =>
                           {
                               string strReg = e.Attribute("mask") != null ? e.Attribute("mask").Value : String.Empty;
                               try
                               {
                                   MatchCollection tmpMatch = Regex.Matches(TrackNumber, strReg);
                                   return tmpMatch.Count > 0;
                               }
                               catch (Exception err)
                               {
                                   Debug.WriteLine(String.Format("Поток {0}: Метод GetPostServices: {1}",
                                                             Thread.CurrentThread.GetHashCode(), err.Message));
                               }
                               return false;
                           });

            // получили данные теперь вернуть в удобоваримом виде
            var tmp1 = SericesInfoInList(activeServices);

            // сделать запрос на осноывнии track number

            activeServices = services
                .Where(e =>
                {
                    string countryID = e.Attribute("countryid") != null ? e.Attribute("countryid").Value : String.Empty;
                    return countryID.Equals(CountryDestanationID);
                });

            // получили данные теперь вернуть в удобоваримом виде
            var tmp2 = SericesInfoInList(activeServices);

            return tmp1.Concat(tmp2);

        }

        private IList<PostServiceInfo> SericesInfoInList(IEnumerable<XElement> aActiveServices)
        {
            IList<PostServiceInfo> result = new List<PostServiceInfo>();
            
            foreach (var activeService in aActiveServices)
            {

                PostServiceInfo info = new PostServiceInfo();
                info.Id = activeService.Attribute("id") != null ? int.Parse(activeService.Attribute("id").Value) : -1;
                info.CountryID = activeService.Attribute("countryid") != null ? int.Parse(activeService.Attribute("countryid").Value) : -1;
                info.Sid = activeService.Attribute("sid") != null ? activeService.Attribute("sid").Value : String.Empty;
                info.Name = activeService.Attribute("name") != null
                                ? activeService.Attribute("name").Value
                                : String.Empty;

                info.Auto = activeService.Attribute("auto") != null
                                ? int.Parse(activeService.Attribute("auto").Value)
                                : -1;

                info.Lang = activeService.Attribute("lang") != null
                                ? activeService.Attribute("lang").Value
                                : String.Empty;

                info.Mask = activeService.Attribute("mask") != null
                                ? activeService.Attribute("mask").Value
                                : String.Empty;

                info.Preparse = activeService.Attribute("preparse") != null
                                ? activeService.Attribute("preparse").Value
                                : String.Empty;

                info.Url = activeService.Attribute("url") != null
                                ? activeService.Attribute("url").Value
                                : String.Empty;

                info.ViewUrl = activeService.Attribute("viewurl") != null
                                   ? activeService.Attribute("viewurl").Value
                                   : String.Empty;

                info.Post = activeService.Attribute("post") != null
                                ? int.Parse(activeService.Attribute("post").Value)
                                : -1;

                info.Postflds = activeService.Attribute("postflds") != null
                                    ? activeService.Attribute("postflds").Value
                                    : String.Empty;

                info.Fail = activeService.Attribute("fail") != null
                                ? activeService.Attribute("fail").Value
                                : String.Empty;

                info.Done = activeService.Attribute("done") != null
                                ? activeService.Attribute("done").Value
                                : String.Empty;

                info.InfoPre = activeService.Attribute("infopre") != null
                                   ? activeService.Attribute("infopre").Value
                                   : String.Empty;

                info.Info = activeService.Attribute("info") != null
                                ? activeService.Attribute("info").Value
                                : String.Empty;

                info.InfoSes = activeService.Attribute("info_ses") != null
                                   ? activeService.Attribute("info_ses").Value
                                   : String.Empty;

                info.DateSe = activeService.Attribute("date_se") != null
                                  ? activeService.Attribute("date_se").Value
                                  : String.Empty;

                info.DateFmt = activeService.Attribute("date_fmt") != null
                                   ? activeService.Attribute("date_fmt").Value
                                   : String.Empty;

                info.DateDlm = activeService.Attribute("date_dlm") != null
                                   ? activeService.Attribute("date_dlm").Value
                                   : String.Empty;

                info.TimeSe = activeService.Attribute("time_se") != null
                                  ? activeService.Attribute("time_se").Value
                                  : String.Empty;

                info.TimeFmt = activeService.Attribute("time_fmt") != null
                                   ? activeService.Attribute("time_fmt").Value
                                   : String.Empty;

                info.TimeDdlm = activeService.Attribute("time_dlm") != null
                                    ? activeService.Attribute("time_dlm").Value
                                    : String.Empty;

                info.HDRS = activeService.Attribute("hdrs") != null
                                ? activeService.Attribute("hdrs").Value
                                : String.Empty;


                result.Add(info);
            }

            return result;
        }
    }
}
